local m = require('utils.vim')
local e = require('utils.editor')

m.map("n", "<M-h>", function()
    local common_keys = require('helper.common_keys')
    local strings = require('plenary.strings')
    local buf = vim.api.nvim_create_buf(false, true)
    local lines = {}
    local max_before_width = 0

    -- First pass: Calculate the maximum width of the before_colon part
    for _, line in ipairs(common_keys) do
        local before_colon = line:match("^([^:]+):")
        if before_colon then
            local width = strings.strdisplaywidth(before_colon)
            if width > max_before_width then
                max_before_width = width
            end
        end
    end

    for _, line in ipairs(common_keys) do
        local before_colon, after_colon = line:match("^([^:]+):(.*)")
        if before_colon then
            local padding = max_before_width - strings.strdisplaywidth(before_colon)
            local padded_before = " " .. before_colon .. "　" .. string.rep(" ", padding) -- use a big blank space char (　)
            table.insert(lines, padded_before .. " " .. after_colon)
        else
            table.insert(lines, line)
        end
    end
    vim.api.nvim_buf_set_lines(buf, 0, -1, false, lines)

    -- Add syntax highlighting for the part before and after the colon
    for i, line in ipairs(lines) do
        local before_colon, after_colon = line:match("^([^　]+)　(.*)") --use a big blank space char (　)
        if before_colon then
            vim.api.nvim_buf_add_highlight(buf, -1, "WhichKey", i - 1, 2, #before_colon - 1)
            vim.api.nvim_buf_add_highlight(buf, -1, "Normal", i - 1, #before_colon + 1, #line)
        end
    end

    -- Calculate window dimensions
    local width = math.max(unpack(vim.tbl_map(function(line) return #line end, common_keys))) + 10
    local height = #common_keys + 2

    -- Get current editor dimensions
    local ui = vim.api.nvim_list_uis()[1]
    local screen_width = ui.width
    local screen_height = ui.height

    -- Calculate centered position
    local col = math.floor((screen_width - width) / 2)
    local row = math.floor((screen_height - height) / 2)

    -- Configure buffer to hide cursor
    vim.api.nvim_buf_set_option(buf, "bufhidden", "wipe")
    vim.api.nvim_buf_set_option(buf, "buftype", "nofile")

    -- Create floating window without cursor
    local win = vim.api.nvim_open_win(buf, true, {
        relative = "editor",
        width = width,
        height = height,
        col = col,
        row = row,
        style = "minimal",
        border = "rounded",
        title = "Common Key Usage",
        title_pos = "center",
        noautocmd = true,
    })

end,{desc="show common key help"})
-- EOP
